<?php

namespace App\Http\Controllers\Admin;

use App\Services\CommentService;
use Illuminate\Http\Request;
use Laravel\Lumen\Routing\Controller;

class CommentController extends Controller
{

    private $commentService;

    public function __construct(CommentService $commentService)
    {
        $this->commentService = $commentService;
    }

    public function index()
    {
        return view('admin.comment.index');
    }

    public function list(Request $request)
    {
        $this->validate($request, [
            'article_id' => 'bail|integer',
            'name'       => 'bail|string',
            'is_reply'   => 'bail|integer|in:0,1',
            'start_time' => 'bail|date_format:Y-m-d',
            'end_time'   => 'bail|date_format:Y-m-d|after_or_equal:start_time',
            'limit'      => 'bail|integer',
        ]);

        $where = [];

        if ($request->filled('article_id')) {
            $where[] = ['article_id', $request->input('article_id')];
        }

        if ($request->filled('name')) {
            $where[] = ['name', $request->input('name')];
        }

        if ($request->filled('is_reply')) {
            if ($request->input('is_reply') == 0) {
                $where[] = ['reply_content', ''];
            } else {
                $where[] = ['reply_content', '!=', ''];
            }
        }

        if ($request->filled('start_time')) {
            $time = strtotime($request->input('start_time'));
            $where[] = ['created', '>=', $time];
        }

        if ($request->filled('end_time')) {
            $time = strtotime($request->input('end_time') . ' 23:59:59');
            $where[] = ['created', '<=', $time];
        }

        $limit = $request->input('limit', 15);
        $data = $this->commentService->getList($where, $limit);

        return success($data);
    }

    public function reply(Request $request)
    {
        if ($request->isMethod('get')) {
            $id = $request->input('id', 0);
            $comment = $this->commentService->find($id);
            $data = [
                'id'            => $comment->id,
                'reply_content' => $comment->reply_content,
            ];
            return view('admin.comment.reply', $data);
        }

        $this->validate($request, [
            'id'            => 'bail|required|integer',
            'reply_content' => 'bail|string|max:65535',
        ]);

        $id = $request->input('id');
        $replyContent = $request->input('reply_content');
        $this->commentService->reply($id, $replyContent);

        return success();
    }

    public function del(Request $request)
    {
        $ids = $request->input('ids', '');
        $ids = explode(',', $ids);
        $this->commentService->del($ids);
        return success();
    }

}
